﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using NCMIS.ObjectModel.MetaData;

namespace NCMIS.ObjectModel
{
    /// <summary>
    /// Represents a CMIS object property of type <see cref="System.DateTime"/>.
    /// </summary>
    [DataContract(Name = "propertyDateTime", Namespace = CmisNs.Cmis)]
    public class CmisPropertyDateTime : CmisProperty
    {
        [DataMember(Name = "value")]
        public new DateTime[] Value
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the single value from this instance. If multiple values exists, the first value is returned.
        /// If no value exists the current date is returned.
        /// </summary>
        [IgnoreDataMember]
        public DateTime SingleValue
        {
            get
            {
                if (this.Value.Length > 0)
                    return this.Value[0];
                return DateTime.Now;
            }
        }

        /// <summary>
        /// Converts an array of <see cref="System.DateTime"/> objects as an array of <see cref="System.DateTimeOffset"/> objects formated as <see cref="System.String"/> objects.
        /// </summary>
        /// <param name="dateTimes">The <see cref="System.DateTime"/> objects to convert.</param>
        /// <returns>Array of <see cref="System.String"/> objects.</returns>
        public static string[] ParseDateTime(DateTime[] dateTimes)
        {
            List<string> dateTimeOffsetList = new List<string>();
            foreach (DateTime dateTime in dateTimes)
            {
                dateTimeOffsetList.Add(XmlConvert.ToString(new DateTimeOffset(DateTime.Now)));
            }
            return dateTimeOffsetList.ToArray();
        }

        /// <summary>
        /// Returns a <see cref="System.Xml.Linq.XElement"/> that represents the current instance.
        /// </summary>
        /// <returns>A <see cref="System.Xml.Linq.XElement"/> that represents the current instance.</returns>
        public override XElement ToXElement()
        {
            XNamespace ns = CmisNs.Cmis;
            XElement propertyElement = new XElement(ns + "propertyDatetime", new XAttribute("propertyDefinitionId", this.PropertyDefinitionId));
            if (this.Value != null)
            {
                propertyElement.Add(new XElement(ns + "value", ParseDateTime(this.Value)));
                if (this.LocalName != null) propertyElement.SetAttributeValue("localName", this.LocalName);
                if (this.DisplayName != null) propertyElement.SetAttributeValue("displayName", this.DisplayName);
                if (this.QueryName != null) propertyElement.SetAttributeValue("queryName", this.QueryName);
            }

            return propertyElement;
        }
    }
}
